package com.nutrition.health.service.impl;

import com.nutrition.health.service.OCRService;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;

@Service
public class OCRServiceImpl implements OCRService {

    private static final Logger logger = LoggerFactory.getLogger(OCRServiceImpl.class);
    
    @Value("${app.image-upload-dir}")
    private String uploadDir;
    
    @Override
    public String extractTextFromImage(MultipartFile image) {
        try {
            // 创建临时文件
            String originalFilename = image.getOriginalFilename();
            String extension = originalFilename != null ?
                originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
            String filename = UUID.randomUUID().toString() + extension;
            
            // 确保上传目录存在
            File directory = new File(uploadDir);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            
            // 保存文件
            File tempFile = new File(directory, filename);
            try (FileOutputStream fos = new FileOutputStream(tempFile)) {
                fos.write(image.getBytes());
            }
            
            try {
                // 使用 Tesseract 进行 OCR
                ITesseract tesseract = new Tesseract();
                
                // 设置语言为中文和英文
                tesseract.setLanguage("chi_sim+eng");
                
                // 执行 OCR
                String result = tesseract.doOCR(tempFile);
                
                logger.info("OCR 结果: {}", result);
                return result;
            } catch (UnsatisfiedLinkError | NoClassDefFoundError e) {
                // Tesseract 库未安装或不可用
                logger.warn("Tesseract OCR 库未安装或不可用，无法进行 OCR 处理: {}", e.getMessage());
                return "OCR_NOT_AVAILABLE";
            } catch (TesseractException e) {
                logger.warn("OCR 处理时出错，返回空结果: {}", e.getMessage());
                return "OCR_ERROR";
            } finally {
                // 删除临时文件
                tempFile.delete();
            }
        } catch (IOException e) {
            logger.error("处理图片文件时出错", e);
            return "IMAGE_PROCESSING_ERROR";
        }
    }
}